<!--工作岗位管理-->
<template>
  <div id="upmsDataSource" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入数据源名称" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="数据源编码" prop="code" width="160">
          <template slot-scope="scope">
            <copy-text :content="scope.row.code" position="left" />
          </template>
        </el-table-column>
        <el-table-column label="数据源名称" prop="name" width="100" />
        <el-table-column label="数据库类型" prop="dbType" width="100" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{ scope.row.dbType | dictFormat }}</template>
        </el-table-column>
        <el-table-column label="驱动类" prop="dbDriver" width="200" :show-overflow-tooltip="true" />
        <el-table-column label="数据源地址" prop="dbUrl" min-width="300" :show-overflow-tooltip="true" />
        <el-table-column label="数据库名称" prop="dbName" width="130" :show-overflow-tooltip="true" />
        <el-table-column label="备注" prop="remark" width="300" :show-overflow-tooltip="true" />

        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="upmsDataSourceRules"
          :model="upmsDataSourceRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="数据源编码:" prop="code">
            <el-input v-model="upmsDataSourceRecord.code" maxlength="12" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="数据源名称:" prop="name">
            <el-input v-model="upmsDataSourceRecord.name" maxlength="50" show-word-limit placeholder="请输入" />
          </el-form-item>

          <el-form-item label="数据库类型:" prop="dbType">
            <data-dict-select v-model="upmsDataSourceRecord.dbType" :code="'dbType'" placeholder="请选择" />
          </el-form-item>
          <el-form-item label="驱动类:" prop="dbDriver">
            <el-input v-model="upmsDataSourceRecord.dbDriver" maxlength="200" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="数据源地址:" prop="dbUrl">
            <el-input
              v-model="upmsDataSourceRecord.dbUrl"
              :rows="4"
              type="textarea"
              maxlength="300"
              show-word-limit
              placeholder="请输入" />
          </el-form-item>
          <el-form-item label="数据库名称:" prop="dbName">
            <el-input v-model="upmsDataSourceRecord.dbName" maxlength="50" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="用户名:" prop="dbUsername">
            <el-input v-model="upmsDataSourceRecord.dbUsername" maxlength="50" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="密码:" prop="dbPassword">
            <el-input v-model="upmsDataSourceRecord.dbPassword" maxlength="100" show-word-limit placeholder="请输入">
              <template slot="append">
                <el-button @click="testConnect">测试连接</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="upmsDataSourceRecord.remark"
              :rows="4"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      upmsDataSourceRecord: {},
      upmsDataSourceRules: {
        code: [
          { required: true, message: '请输入数据源编码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入数据源名称', trigger: 'blur' }
        ],
        dbType: [
          { required: true, message: '请输入数据库类型', trigger: 'blur' }
        ],
        dbDriver: [
          { required: true, message: '请输入驱动类', trigger: 'blur' }
        ],
        dbUrl: [
          { required: true, message: '请输入数据源地址', trigger: 'blur' }
        ],
        dbName: [
          { required: true, message: '请输入数据库名称', trigger: 'blur' }
        ],
        dbUsername: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        dbPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      dbDriverMap: {
        // MySQL 数据库
        '01': { dbDriver: 'com.mysql.jdbc.Driver' },
        // MySQL5.7+ 数据库
        '02': { dbDriver: 'com.mysql.cj.jdbc.Driver' },
        // Oracle
        '03': { dbDriver: 'oracle.jdbc.OracleDriver' },
        // SQLServer 数据库
        '04': { dbDriver: 'com.microsoft.sqlserver.jdbc.SQLServerDriver' },
        // postgresql 数据库
        '05': { dbDriver: 'org.postgresql.Driver' },
        // marialDB 数据库
        '06': { dbDriver: 'org.mariadb.jdbc.Driver' },
        // H2 数据库
        '07': { dbDriver: 'org.h2.Driver' },
        // DB2 数据库
        '08': { dbDriver: 'com.ibm.db2.jcc.DB2Driver' },
        // SQLite 数据库
        '09': { dbDriver: 'org.sqlite.JDBC' },
        // 其他数据库
        '15': { dbDriver: '' }
      },
      dbUrlMap: {
        // MySQL 数据库
        '01': { dbUrl: 'jdbc:mysql://127.0.0.1:3306/chiship_common_upms?characterEncoding=UTF-8&useUnicode=true&useSSL=false' },
        // MySQL5.7+ 数据库
        '02': { dbUrl: 'jdbc:mysql://127.0.0.1:3306/chiship_common_upms?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai' },
        // Oracle
        '03': { dbUrl: 'jdbc:oracle:thin:@127.0.0.1:1521:ORCL' },
        // SQLServer 数据库
        '04': { dbUrl: 'jdbc:sqlserver://127.0.0.1:1433;SelectMethod=cursor;DatabaseName=jeecgboot' },
        // Postgresql 数据库
        '05': { dbUrl: 'jdbc:postgresql://127.0.0.1:5432/chiship_common_upms' },
        // Mariadb 数据库
        '06': { dbUrl: 'jdbc:mariadb://127.0.0.1:3306/chiship_common_upms?characterEncoding=UTF-8&useSSL=false' },
        // H2 数据库
        '07': { dbUrl: 'jdbc:h2:tcp://127.0.0.1:8082/chiship_common_upms' },
        // DB2 数据库
        '08': { dbUrl: 'jdbc:db2://127.0.0.1:50000/chiship_common_upms' },
        // 其他数据库
        '15': { dbUrl: '' }
      }
    }
  },
  watch: {
    'upmsDataSourceRecord.dbType': function(val) {
      if (val) {
        var index = this.common.dataDictFormat(val).typeCode
        const dbDriver = this.dbDriverMap[index].dbDriver
        const dbUrl = this.dbUrlMap[index].dbUrl
        this.upmsDataSourceRecord = {
          ...this.upmsDataSourceRecord,
          dbDriver: dbDriver,
          dbUrl: dbUrl
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 表格自带方法开始
    /** 全选/反选 */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /** 表格行数据单击 */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /** 表格列排序 */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }

      this.fetchData()
    },

    async fetchData() {
      const response = await this.$store.dispatch('upmsDataSourcePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.upmsDataSourceRecord = {}
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增三方数据源'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('upmsDataSourceSave', this.upmsDataSourceRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.upmsDataSourceRecord = Object.assign({}, row) // copy obj
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑三方数据源'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.upmsDataSourceRecord)
          this.$store.dispatch('upmsDataSourceUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    // 测试连接
    testConnect() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.upmsDataSourceRecord)
          this.$store.dispatch('upmsDataSourceTestConnect', tempData).then(response => {
            this.msgSuccess('数据库连接成功')
          }).catch((_) => { })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('upmsDataSourceRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
